package com.parse.dxf.service.impl;

import com.parse.dxf.utils.DxfParseUtils;
import com.parse.dxf.entity.DxfInfo;
import com.parse.dxf.entity.RoomInfo;
import com.parse.dxf.mapper.DxfInfoMapper;
import com.parse.dxf.service.DxfInfoService;
import com.parse.dxf.service.RoomInfoService;
import org.kabeja.dxf.DXFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class DxfinfoServiceImpl implements DxfInfoService {

    //指定文件上传的存储路径，把路径写在配置文件中，通过 @Value 注解来获取该属性值
    @Value("${spring.servlet.multipart.location}")
    private String savePath;


    /**
     * 保存文件的相对目录
     */
    private String relativeDirectory = "files/";

    @Autowired
    private DxfInfoMapper dxfInfoMapper;

    @Autowired
    private RoomInfoService roomInfoService;

    @Override
    public int insert(DxfInfo data) {
        return dxfInfoMapper.insert(data);
    }

    @Override
    public DxfInfo uploadDxf(MultipartFile file) {
        if (file.isEmpty()) {
            return null;
        }
        try {

            //先解析dxf文件
            DXFDocument dcc = DxfParseUtils.parseDxf(file.getInputStream());
            if (dcc == null) {
                return null;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String newfile = UUID.randomUUID() + "_" + fileName;
            // 指定文件夹路径
            String directoryPath = savePath + "/" + relativeDirectory;
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String path = directoryPath + newfile;
            // 把文件数据存储到本地磁盘上
            file.transferTo(new File(path));
            DxfInfo dxfInfo = new DxfInfo();
            dxfInfo.setName(fileName);
            dxfInfo.setFilePath(relativeDirectory + newfile);
            dxfInfo.setUploadTime(LocalDateTime.now());
            // 添加到数据库中
            insert(dxfInfo);
            List<RoomInfo> rooms = DxfParseUtils.parseDxfRooms(dcc, dxfInfo.getId());
            roomInfoService.insert(rooms);
            return dxfInfo;

        } catch (Exception e) {
            return null;
        }
    }


    @Override
    public DxfInfo getDxfInfoById(int id) {
        return dxfInfoMapper.selectById(id);
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @param response 响应对象
     * @throws IOException
     */
    @Override
    public void downloadFile(String fileName, HttpServletResponse response) throws IOException {
        String filePath = savePath + "/" + relativeDirectory + fileName;
        File file = new File(filePath);

        if (file.exists()) {
            // Set the content type and attachment header
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            // Write file to response output stream
            try (InputStream inputStream = new FileInputStream(file);
                 ServletOutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("File not found");
        }
    }
}
